using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using ECatalog.Models.Organizations;

namespace ECatalog.Models.Organizations
{
    public class OrganizationRepository : IOrganizationRepository
    {
        public Organization[] All()
        {
            using (var db = new DbContainer())
            {
                return db.Organizations.ToArray();
            }
        }

        public Organization Add(Organization organization)
        {
            using (var db = new DbContainer())
            {
                try
                {
                    db.Organizations.Add(organization);
                    db.SaveChanges();
                    return organization;
                }
                catch (Exception)
                {
                   
                }
            }
            return null;
        }

        public Organization GetOrganizationById(int id)
        {
            using (var db = new DbContainer())
            {
                return db.Organizations.FirstOrDefault(o=>o.OrganizationId==id);
            }
        }

        public void Edit(Organization organization)
        {
            using (var db = new DbContainer())
            {
                db.Entry(organization).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        public void Delete(int organizationId)
        {
            using (var db = new DbContainer())
            {
                try
                {
                    var organization = db.Organizations.SingleOrDefault(s => s.OrganizationId == organizationId);
                    db.Organizations.Remove(organization);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                }
            }
        }
    }
}